package com.application.api.intercept;

import com.application.api.entity.ResultEntity;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.platform.constant.ConstantAuth;
import com.platform.constant.ConstantInit;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.syslog.Syslog;
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

/**
 * Created by ly on 2016/3/1.
 */
public class ApiInterceptor implements Interceptor {

    private static Logger log = Logger.getLogger(ApiInterceptor.class);

    @Override
    public void intercept(Invocation invoc) {
        BaseController contro = (BaseController) invoc.getController();
        Syslog reqSysLog = contro.getReqSysLog();
        try {
            invoc.invoke();
            toJson(contro, "", "Success");
        } catch (Exception e) {
            String expMessage = e.getMessage();
            // 开发模式下的异常信息
            if (Boolean.parseBoolean(PropKit.get(ConstantInit.config_devMode))) {
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                e.printStackTrace(new PrintWriter(buf, true));
                expMessage = buf.toString();
            }

            log.error("业务逻辑代码遇到异常时保存日志!");
            reqSysLog.set(Syslog.column_status, "0");// 失败
            reqSysLog.set(Syslog.column_description, expMessage);
            reqSysLog.set(Syslog.column_cause, "3");// 业务代码异常

            log.error("返回失败提示页面!Exception = " + e.getMessage());

//			if(e instanceof RuntimeException){
//				expMessage = "自定义异常描述11" + expMessage;
//			} else if(e instanceof RuntimeException){
//				expMessage = "自定义异常描述22" + expMessage;
//			}

            toJson(contro, ConstantAuth.auth_exception, "业务逻辑代码遇到异常Exception = " + expMessage);
        } finally {
            MDC.remove("userId");
            MDC.remove("userName");
        }
    }

    private void toJson(BaseController contro, String type, String msg) {
        ResultEntity res = null;
        if (type.equals(ConstantAuth.auth_no_login)) {// 未登录处理
            res = new ResultEntity(HttpStatus.SC_UNAUTHORIZED, "未登录");
        } else if (type.equals(ConstantAuth.auth_exception)) {
            res = new ResultEntity(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
        }

        contro.renderJson(res);
    }
}
